#include "building.h"

Building::Building(QPoint enterence, QPixmap buildingPixmap, QGraphicsScene *scene)
    : QGraphicsPixmapItem(buildingPixmap)
{
    scene->addItem(this);

    setAcceptHoverEvents(true);

    setData(ITEM_TYPE,GameItems::Building);

    overlayPixmap = buildingPixmap;
    overlayPixmap.fill(QColor(255,0,0,128));
    overlayPixmap.setAlphaChannel(pixmap());

    toolTip = new BuildingToolTip(scene);
    infectedPeople = 0;
    buildingHealth = 0;

    enterencePoint = enterence;

}

void Building::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    emit clicked(this);
}

void Building::addPerson(Person *newPerson)
{
    currentPeople.append(newPerson);
}

void Building::removePerson(Person *oldPerson)
{
    if (currentPeople.indexOf(oldPerson) > -1)
        currentPeople.removeAt(currentPeople.indexOf(oldPerson));
}

void Building::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QGraphicsPixmapItem::paint(painter,option,widget);

    // If the building is infected draw the red overlay
 //   if (infected)
 //       painter->drawPixmap(0,0,overlayPixmap);
}

void Building::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
    toolTip->updateToolTip(event->scenePos(),buildingHealth, currentPeople.length(), infectedPeople);
    toolTip->show();
}

void Building::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{
    toolTip->hide();
}

void Building::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    toolTip->updateToolTip(event->scenePos(),buildingHealth, currentPeople.length(), infectedPeople);
}

void Building::advance(int phase)
{
    if ((phase == 0) && (toolTip->isVisible()))
    {
        int newHealth = 0, newInfected = 0;

        for (int index = 0; index < currentPeople.length(); index++)
        {
            newHealth += currentPeople.at(index)->stats->Hp;
            if (currentPeople.at(index)->virus != 0)
                newInfected++;
        }

        buildingHealth = ((newHealth/currentPeople.length())/1000.0);
        infectedPeople = newInfected;
    }
}

QList<Person*> Building::CurrentPeopleAccessor()
{
    return currentPeople;
}

QPoint Building::getEnterencePoint()
{
    return enterencePoint;
}
